//
//  YZMLockView.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/4/20.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMLockView.h"

static const float lock_view_circle_margin = 52;
static const float lock_view_circle_diameter = 68;

static const float lock_view_circle_diameter_small = 24;
static const float lock_view_circle_alpha = 1.0;
static const float lock_view_line_width = 2.0;
static const NSInteger lock_view_tag_for_base = 10000;

@implementation YZMLockView{
    
    NSMutableArray *_buttonArray;
    NSMutableArray *_selectedButtonArray;
    NSMutableArray *_wrongButtonArray;
    
    CGPoint _nowPoint;
    
    NSTimer *_timer;
    
    BOOL _isDrawing;
    
    UIColor *_selectedColor;
    UIColor *_normalColor;
}


- (id)init{
    
    self = [super initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 240)];
    
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        self.clipsToBounds = YES;
        [self initCircles];
    }
    
    return self;
}

- (void)initCircles{

    _selectedColor = [YZMAppStyle colorForYellowButton];
    _normalColor = [YZMAppStyle colorForLightGrayText];
    
    _buttonArray = [NSMutableArray array];
    _selectedButtonArray = [NSMutableArray array];
    for (int i= 0; i<3; i++) {
        
        UIView *view = [UIView new];
        [self addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *maker){
            
            maker.left.equalTo(self).offset(lock_view_circle_margin);
            maker.right.equalTo(self).offset(-lock_view_circle_margin);
            maker.height.mas_equalTo(lock_view_circle_diameter);
            [self addSubview:view];
            
            if (i==0) {
                
                maker.top.equalTo(self);
                maker.width.equalTo(self.mas_height);
                
            }else if(i==1){
                
                maker.centerY.equalTo(self);
            }else if(i==2){
                
                maker.bottom.equalTo(self);
            }
            
        }];
        
        for (int j=0; j<3; j++) {
            
            float magin_circle = lock_view_circle_diameter/2 - lock_view_circle_diameter_small/2;
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setImage:[self.class roundSelectedImageWithColor:_selectedColor diameter:lock_view_circle_diameter] forState:UIControlStateSelected];
            [button setImageEdgeInsets:UIEdgeInsetsMake(magin_circle, magin_circle, magin_circle, magin_circle)];
            button.alpha = lock_view_circle_alpha;
            button.tag = i*3+j + lock_view_tag_for_base +1;
            button.layer.cornerRadius = lock_view_circle_diameter/2;
            button.layer.masksToBounds = YES;
            button.layer.borderWidth = 1;
            button.layer.borderColor = [YZMAppStyle colorForLightGrayText].CGColor;
            button.userInteractionEnabled = NO;
            [_buttonArray addObject:button];
            [self addSubview:button];
            [button mas_makeConstraints:^(MASConstraintMaker *maker){
                
                maker.width.height.mas_equalTo(lock_view_circle_diameter);
                maker.top.equalTo(view);
                
                if (j==0) {
                    
                    maker.left.equalTo(view);
                    
                }else if(j==1){
                    
                    maker.centerX.equalTo(view);
                }else if(j==2){
                    
                    maker.right.equalTo(view);
                }
            }];
        }
    }
}

#pragma mark - 事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _isDrawing = NO;
    CGPoint point = [[touches anyObject] locationInView:self];
    [self updateFingerPosition:point];
    
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    _isDrawing = YES;
    
    CGPoint point = [[touches anyObject] locationInView:self];
    [self updateFingerPosition:point];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self endPosition];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self endPosition];
}


#pragma mark - 绘制连线
- (void)drawRect:(CGRect)rect
{
    if (_selectedButtonArray.count > 0) {
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        [_selectedColor set]; // 正误线条色
        CGContextSetLineWidth(context, lock_view_line_width);
        
        // 画之前线s
        CGPoint addLines[9];
        int count = 0;
        for (UIButton* button in _selectedButtonArray) {
            CGPoint point = CGPointMake(button.center.x, button.center.y);
            addLines[count++] = point;
            
            // 画中心圆
            CGRect circleRect = CGRectMake(button.center.x- lock_view_line_width/2,
                                           button.center.y - lock_view_line_width/2,
                                           lock_view_line_width,
                                           lock_view_line_width);
            CGContextSetFillColorWithColor(context, _selectedColor.CGColor);
            CGContextFillEllipseInRect(context, circleRect);
        }
        CGContextSetLineJoin(context, kCGLineJoinRound);
        CGContextAddLines(context, addLines, count);
        CGContextStrokePath(context);
        //*/
        
        // 画当前线
        if (_selectedButtonArray.count < 9) {
            UIButton* lastButton = _selectedButtonArray.lastObject;
            CGContextMoveToPoint(context, lastButton.center.x, lastButton.center.y);
            CGContextAddLineToPoint(context, _nowPoint.x, _nowPoint.y);
            CGContextStrokePath(context);
        }
    }
}

#pragma mark - 处理
// 当前手指位置
- (void)updateFingerPosition:(CGPoint)point{
    
    _nowPoint = point;
    
    for (UIButton *thisbutton in _buttonArray) {
        CGFloat xdiff =point.x-thisbutton.center.x;
        CGFloat ydiff=point.y - thisbutton.center.y;
        
        if (fabs(xdiff) < lock_view_circle_diameter/2 &&fabs(ydiff) <lock_view_circle_diameter/2){
            
            // 未选中的才能加入
            if (!thisbutton.selected) {
                thisbutton.selected = YES;
                thisbutton.layer.borderColor = _selectedColor.CGColor;
                [_selectedButtonArray  addObject:thisbutton];
            }
        }
    }
    [self setNeedsDisplay];
}

- (void)endPosition
{
    _isDrawing = NO;
    
    UIButton *strbutton;
    NSString *string=@"";
    
    // 生成密码串
    for (int i=0; i < _selectedButtonArray.count; i++) {
        strbutton = _selectedButtonArray[i];
        string= [string stringByAppendingFormat:@"%@",@(strbutton.tag-lock_view_tag_for_base)];
    }
    
    [self clearColorAndSelectedButton]; // 清除到初始样式
    
    if ([self.delegate respondsToSelector:@selector(createLockString:)]) {
        if (string && string.length>0) {
            [self.delegate createLockString:string];
        }
    }
}

- (void)clearSelectedButton
{
    // 换到下次按时再弄
    for (UIButton *thisButton in _buttonArray) {
        [thisButton setSelected:NO];
        thisButton.layer.borderColor = _normalColor.CGColor;
    }
    [_selectedButtonArray removeAllObjects];
    
    [self setNeedsDisplay];
}

- (void)clearColorAndSelectedButton
{
    if (!_isDrawing) {
        [self clearSelectedButton];
    }
    
}


+ (UIImage *)roundSelectedImageWithColor:(UIColor *)color diameter:(float)diameter{
    
    CGSize imageSize = CGSizeMake(diameter, diameter);
    
    UIGraphicsBeginImageContext(imageSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, CGRectMake(0, 0, diameter, diameter));
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CALayer *imageLayer = [CALayer layer];
    imageLayer.frame = CGRectMake(0, 0, theImage.size.width, theImage.size.height);
    imageLayer.contents = (id) theImage.CGImage;
    
    imageLayer.masksToBounds = YES;
    imageLayer.cornerRadius = diameter/2;
    imageLayer.borderColor = color.CGColor;
    imageLayer.borderWidth = 1;
    
    UIGraphicsBeginImageContext(theImage.size);
    [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return roundedImage;
}

@end

